<?php

namespace app\admin\controller\course;

use app\admin\model\course\ClassesConfig;
use app\admin\model\course\OrderGoods;
use app\admin\model\course\OrderLog;
use app\common\controller\Backend;
use app\common\model\User;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\course\Order
     */
    protected $model = null;
    protected $noNeedRight = ["selectpage","selectpage_order_goods"];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\course\Order;
        $statusList = $this->model->getStatusList();
        $this->view->assign("statusList", $statusList);
        $this->assignconfig("statusList", $statusList);

        $typeList = $this->model->getTypeList();
        $this->view->assign("typeList", $typeList);
        $this->assignconfig("typeList", $typeList);

        $schoolModel = new \app\admin\model\user\School();
        $schoolGroup = $schoolModel->getAllSchool();
        $this->assignconfig("schoolGroup",$schoolGroup);
    }

    /*
     * 课程
     * */
    public function selectpage_order_goods(){
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        $condition = [];
        if(isset($custom['student_id'])){
            $condition['order_goods.student_id'] = $custom['student_id'];
        }
        if(isset($custom['teacher_id'])){
            $condition['order_goods.teacher_id'] = $custom['teacher_id'];
        }
        $day = '';
        if(isset($custom['day'])){
            $day = $custom['day'];

        }
        $orderGoodsModel = new OrderGoods();
        $list = $orderGoodsModel->getTimeTable($condition,$day);
        foreach ($list as $key => $value){
            $value['classes_name'] = $value['teacher']['nickname']."-".$value['course_name']."-".$value['classes_name']."-".$value['time_name'];
        }
        return json([
            "list" => $list,
            "total" => count($list)
        ]);
    }



    /**
     * 手动录单
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);


        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        Db::startTrans();
        try {
            $user = User::get($params['user_id']);
            if(empty($params['config'])){
                exception("请选择班次");
            }
            $time_arr = json_decode($params['config'],true);
            if(count($time_arr) == 0 ){
                exception("请选择班次");
            }
//            dump($params);
//            dump($time_arr);
//            exit;
            $params['type'] = $this->model::TYPE_ADMIN;
            $params['pay_type'] = $this->model::TYPE_ADMIN;
            foreach ($time_arr as $key => $value){
                $params['school_id'] = $value['school_id'];
                $params['classes_id'] = $value['classes_id'];
            }
            $admin_msg = $this->auth->nickname."后台录单";
            $orderId = $this->model->createOrder($user, $params,$time_arr,0,$admin_msg);
            $orderInfo = $this->model->where("id", $orderId['order_id'])
                ->find();
            $orderInfo->payOrder($user, "admin", "admin");
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }

        if ($orderId === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /*
   * 恢复停课
   * */
    public function restore_order($ids = null){
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);


            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $params[$this->dataLimitField] = $this->auth->id;
            }
            $surplus_class_hour = $this->request->post("surplus_class_hour");

            if($surplus_class_hour <= 0){
                exception("请填写大于0的剩余课时");
            }
            Db::startTrans();
            try {
                //先取消
                $row->cancelOrder("恢复上课取消老订单");
                //重新下单
                $user = User::get($params['user_id']);
                if(empty($params['config'])){
                    exception("请选择班次");
                }
                $time_arr = json_decode($params['config'],true);
                if(count($time_arr) == 0 ){
                    exception("请选择班次");
                }
//            dump($params);
//            dump($time_arr);
//            exit;
                $params['type'] = $this->model::TYPE_RESTORE;
                $params['pay_type'] = $this->model::TYPE_RESTORE;


                $params['parent_name'] = $row['parent_name'];
                $params['phone_1'] = $row['phone_1'];
                $params['phone_2'] = $row['phone_2'];
                $params['phone_3'] = $row['phone_3'];
                foreach ($time_arr as $key => $value){
                    $params['school_id'] = $value['school_id'];
                    $params['classes_id'] = $value['classes_id'];
                }
                $admin_msg = $this->auth->nickname."恢复上课创建";

                $orderId = $this->model->createOrder($user, $params,$time_arr,0,$admin_msg);


                $newOrderInfo = $this->model->where("id", $orderId['order_id'])
                    ->find();

                $newOrderInfo->payOrder($user, "admin", "admin");


                //消耗课时


                $deal_class_hour = $newOrderInfo['class_hour'] - $surplus_class_hour;
                if($deal_class_hour != 0){
                    if($deal_class_hour > 0){
                        $msg = $this->auth->nickname . "恢复上课,设置剩余课时：{$surplus_class_hour}";
                        $newOrderInfo->useHour($msg, $deal_class_hour);
                    }else{
                        exception("当前课程总课时为：{$newOrderInfo['class_hour']},请检查剩余课程配置");
                    }
                }


                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success("设置成功");
        }
        $this->assign("row",$row);
        $condition = [
//            "user_id" => $this->auth->id,
            "order.id" => $row["id"],
        ];
        $oldOrderInfo = $this->model->getOrderInfo($condition);
        $this->assign("oldOrderInfo",$oldOrderInfo);
        return $this->view->fetch();

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($otherWhere,$where, $sort, $order, $offset, $limit) = $this->buildparams();
            $myWhere = [];
            if(isset($otherWhere['status'])){
                switch ($otherWhere['status']){
                    case 21: //未排课
//                        $myWhere["sign_up_start_time"] = [">",time()];
                        $ids = OrderGoods::where("teacher_id",0)->column("order_id");
                        $myWhere['order.id'] = ["in", $ids];
                        break;
                    case 22: //未排课
//                        $myWhere["sign_up_start_time"] = [">",time()];
                        $ids = OrderGoods::where("teacher_id",">",0)->column("order_id");
                        $myWhere['order.id'] = ["in", $ids];
                        break;

                    default:
                        $myWhere["order.status"] = $otherWhere['status'];
                        break;
                }
            }

            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where($myWhere)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->status_text = $this->model->getStatusText($row->status);

                $orderGoods = \app\admin\model\course\OrderGoods::with(["teacher"=>function($query){
                    $query->withField("nickname");
                }])->where("order_id",$row["id"])->select();
//                dump($orderGoods);exit;

                foreach ($orderGoods as $key => &$value){
                    if(mb_strlen($value["course_name"]) >= 12){
                        $value["course_name"] = mb_substr($value["course_name"], 0, 12) . "...";
                    }
                    $row["order_goods"] = $orderGoods;
                }
                $row->getRelation('user')->visible(['nickname']);
                $row = $this->model->dealOrderInfo($row);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null){
        $row = $this->model->where("id", $ids)->find();

        $is_read = $this->request->request("is_read",0);

        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if(count($params) > 0){
                    Db::startTrans();
                    try {
                        $adminName = $this->auth->nickname;
                        $row->changeTeacher($params,$adminName);
                        Db::commit();
                    } catch (ValidateException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                }

                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $row["status_text"] = $this->model->getStatusText($row->status);
        $row["type_text"] = $this->model->getTypeText($row->type);
        $row["pay_from_text"] = $this->model->getPayFromText($row->pay_from);
        $row["pay_type_text"] = $this->model->getPayTypeText($row->pay_type);
        $orderGoods = OrderGoods::where("order_id",$row["id"])->select();
        $logs = OrderLog::where("order_id", $row["id"])->select();
        $this->assign("row", $row);
        $this->assign("orderGoods", $orderGoods);
        $this->assign("logs", $logs);
        $this->assign("is_read", $is_read);
        return $this->view->fetch();
    }

    /*
     * 修改价格
     * */
    public function change_money($ids){
        $row = $this->model->where("id", $ids)->find();
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $adminName = $this->auth->nickname;
                    $row->changeMoney($params, $adminName);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign("row", $row);
        return $this->view->fetch();
    }

    /*
        * 取消订单
        * */
    public function cancel_order($ids = null){

        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $row->cancelOrder($this->auth->getUserInfo()["nickname"] . "后台取消");
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();

        }
    }

    /*
        * 退款
        * */
    public function refund_order($ids){
//        $ids = $this->request->request("ids");
        $refund_content = $this->request->request("refund_content");

        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);

            Db::startTrans();
            try {
                $order = $this->model->get($params['ids']);
                $user = User::get($order->user_id);
                if($order['type'] == 3){
                    $msg = $this->auth->getUserInfo()["nickname"] . "后台取消";
                }else{
                    $msg = $this->auth->getUserInfo()["nickname"] . "后台退款";
                }

                $row->refundOrder($user, $msg,$params['refund_content'],$params['refund_money']);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();

        }
        $this->assign("row",$row);
        return $this->view->fetch();
    }


    /*
     * 停课
     * */
    public function stop_order($ids = null){
        $row = $this->model->get($ids);
        $stop_content = $this->request->request("stop_content");
        Db::startTrans();
        try {
            $row->stopOrder($stop_content);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("设置成功");
    }




    /*
     * 消耗课时
     * */
    public function use_hour(){
        $ids = $this->request->request("ids");
        $hour = $this->request->request("hour");

        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            Db::startTrans();
            try {

                $msg = $this->auth->getUserInfo()["nickname"] . "消耗课时：{$hour}";
                $row->useHour($msg, $hour);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();

        }
    }

    /**
     * 删除订单
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                if($item['type'] != $this->model::TYPE_ADMIN){
                    exception("只有后台录单的才能删除");
                }
                //删除子订单
                OrderGoods::where("order_id",$item['id'])->delete();
                //删除签到日志
                \app\admin\model\course\OrderSign::where("order_id",$item['id'])->delete();
                //删除订单日志
                OrderLog::where("order_id",$item['id'])->delete();
                $count += $item->delete();

            }
            Db::commit();
        } catch (PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);

        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $otherWhere = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if(isset($filter["status"])){
            $otherWhere["status"] = $filter['status'];
            unset($filter['status']);
        }
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$otherWhere,$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }
}
